package com.ddm.utils;

import com.ddm.properties.UploadImageProperties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.File; // 使用Java标准库的File类
import java.io.FileOutputStream;
import java.io.InputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class DownloadFileUtil {

    @Autowired
    private UploadImageProperties downloadFileProperties;

    /**
     * 利用JSch包实现SFTP下载文件
     * @param remoteFileName 远程文件名
     * @param localFilePath 本地保存路径
     * @return 下载成功返回本地文件路径，失败返回null
     * @throws Exception
     */
    public String sshSftpDownload(String remoteFileName, String localFilePath) throws Exception {
        int port = downloadFileProperties.getPort();
        String user = downloadFileProperties.getUser();
        String password = downloadFileProperties.getPassword();
        String ip = downloadFileProperties.getIp();
        // 服务器文件路径
        String remoteFilePath = downloadFileProperties.getFilepath();

        Session session = null;
        Channel channel = null;
        InputStream in = null;
        FileOutputStream out = null;

        try {
            JSch jSch = new JSch();

            // 创建会话
            if (port <= 0) {
                session = jSch.getSession(user, ip);
            } else {
                session = jSch.getSession(user, ip, port);
            }

            // 校验会话是否创建成功
            if (session == null) {
                throw new Exception("session is null");
            }

            // 设置会话参数
            session.setPassword(password);
            session.setConfig("userauth.gssapi-with-mic", "no");
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(30000);

            // 创建SFTP通道
            channel = session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;

            // 进入远程文件目录
            sftp.cd(remoteFilePath);

            // 准备本地文件
            File localFile = new File(localFilePath);
            // 确保父目录存在
            if (!localFile.getParentFile().exists()) {
                localFile.getParentFile().mkdirs();
            }

            // 下载文件
            in = sftp.get(remoteFileName);
            out = new FileOutputStream(localFile);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }

            System.out.println("文件下载成功: " + localFilePath);
            return localFilePath;

        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("文件下载失败: " + e.getMessage());
        } finally {
            // 关闭流和连接
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }
}